package com.wg.db.redis;

import cn.hutool.core.util.StrUtil;

import java.io.Serializable;

import com.wg.core.exception.InvalidConfigException;

/**
 * Redis 连接配置类
 * 支持单机模式配置，包含连接地址、端口、密码、数据库索引等核心参数
 *
 * @author 少爷123
 */
public class RedisConfig implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 默认主机地址
     */
    public static final String DEFAULT_HOST = "localhost";
    /**
     * 默认端口
     */
    public static final int DEFAULT_PORT = 6379;
    /**
     * 默认数据库索引（0-15）
     */
    public static final int DEFAULT_DB = 0;
    /**
     * 默认密码（无）
     */
    public static final String DEFAULT_PASSWORD = null;

    /**
     * 主机地址
     */
    private String host;
    /**
     * 端口
     */
    private int port;
    /**
     * 密码
     */
    private String password;
    /**
     * 数据库索引
     */
    private int db;

    /**
     * 带参构造函数（用于手动创建配置）
     */
    public RedisConfig(String host, int port, String password, int db) {
        validate(host, port, db);
        this.host = host;
        this.port = port;
        this.password = password;
        this.db = db;
    }

    /**
     * 参数校验
     */
    private void validate(String host, int port, int db) {
        if (StrUtil.isBlank(host)) {
            throw new InvalidConfigException("Redis主机地址不能为空");
        }
        if (port < 0 || port > 65535) {
            throw new InvalidConfigException("Redis端口必须在0-65535之间，当前值：" + port);
        }
        if (db < 0 || db > 15) {
            throw new InvalidConfigException("Redis数据库索引必须在0-15之间，当前值：" + db);
        }
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        if (StrUtil.isBlank(host)) {
            throw new InvalidConfigException("Redis主机地址不能为空");
        }
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        if (port < 0 || port > 65535) {
            throw new InvalidConfigException("Redis端口必须在0-65535之间，当前值：" + port);
        }
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getDb() {
        return db;
    }

    public void setDb(int db) {
        if (db < 0 || db > 15) {
            throw new InvalidConfigException("Redis数据库索引必须在0-15之间，当前值：" + db);
        }
        this.db = db;
    }

    @Override
    public String toString() {
        return "RedisConfig{" +
                "host='" + host + '\'' +
                ", port=" + port +
                ", password='[PROTECTED]'" +
                ", db=" + db +
                '}';
    }

    public String getConnectionKey() {
        return host + ":" + port + "-db" + db;
    }
}